/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ranophoenix.osgijee.webclient.impl.cdi;

import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import ranophoenix.osgijee.core.ModuleExtension;
import ranophoenix.osgijee.webclient.impl.cdi.qualifiers.Initialized;

/**
 *
 * @author ranophoenix
 */
@Named
@ApplicationScoped
public class ApplicationBean {

    @Inject
    private ServiceTracker st;
    @Inject
    private BundleContext bc;
    @Inject
    private ModuleExtensionListener mel;
    private List<ModuleExtension> modules = new ArrayList<ModuleExtension>();

    @Inject
    public void initialize(ServiceTracker st) {
        bc.addServiceListener(mel);        
        loadServices();
    }

    public void afterAddModuleExtension(@Observes @Initialized ModuleExtension module) {
        System.out.println("Module added.");
        modules.add(module);
    }

    public void beforeRemoveModuleExtension(@Observes @Initialized ModuleExtension module) {
        System.out.println("Module removed");
        modules.remove(module);
    }

    public List<ModuleExtension> getModules() {
        return modules;
    }

    private void loadServices() {
        ServiceReference[] srs = st.getServiceReferences();
        if (srs != null) {
            for (ServiceReference sr : srs) {
                ModuleExtension m = (ModuleExtension) bc.getService(sr);
                modules.add(m);
            }
        }
    }    
        
}
